/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.ez2find.backing;

import com.ez2find.manager.AreaManagerLocal;
import com.ez2find.manager.SaleCategorieManagerLocal;
import com.ez2find.manager.SaleManagerLocal;
import com.ez2find.manager.ImageManagerLocal;
import com.ez2find.manager.LocationManagerLocal;
import com.ez2find.manager.RegisterUserManagerLocal;
import com.ez2find.model.Area;
import com.ez2find.model.Sale;
import com.ez2find.model.SaleCategorie;
import com.ez2find.model.Image;
import com.ez2find.model.Location;
import com.ez2find.model.RegisterUser;
import com.ez2find.services.EmailLocal;
import com.ez2find.util.RequestContext;
import com.ez2find.util.SessionContext;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.richfaces.model.UploadItem;

/**
 *
 * @author Administrador
 */
public class SaleBean {

    @EJB
    private SaleManagerLocal ejbSaleManager;
    @EJB
    private SaleCategorieManagerLocal ejbSaleCategorieManager;
    @EJB
    private RegisterUserManagerLocal ejbUserManager;
    @EJB
    private EmailLocal ejbEmail;
    @EJB
    private AreaManagerLocal ejbAreaManager;
    @EJB
    private LocationManagerLocal ejbLocationManager;
    @EJB
    private ImageManagerLocal ejbImageManager;
    private Sale sale;
    private int back;
    private long saleCategorieId;
    private long areaId;
    private String email1;
    private List<UploadItem> uploadItems;
    private int row;
    private boolean linkRPOk;
    private boolean createOk;
    private boolean maskedEmail;
    private int page;
    private String searchValue;
    private String searchType;
    private String searchMinPrice;
    private String searchMaxPrice;
    private boolean onlySearchTitles;
    private boolean hasImage;

    public Sale getSale() {
        if (sale == null) {
            ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
            HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();
            HttpSession session = request.getSession();
            if (session.isNew()) {
                try {
                    String errorPageURL = externalContext.getRequestContextPath() + "/faces/welcome.jsp";
                    externalContext.redirect(errorPageURL);
                    FacesMessage msg = new FacesMessage("The session has bean expired");
                    msg.setSeverity(FacesMessage.SEVERITY_ERROR);
                    FacesContext.getCurrentInstance().addMessage(null, msg);
                    return null;
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                    return null;
                }
            } else {
                SessionBean sessionBean = (SessionBean) SessionContext.getAttribute("sessionBean");
                if (sessionBean.getEjbSession().getSale() != null) {
                    sale = sessionBean.getEjbSession().getSale();
                    if (sale.getPrice() > 0) {
                        searchMinPrice = String.valueOf(sale.getPrice());
                    }
                    if(sale.getTypeReplyTo().equals("masked email"))
                        maskedEmail=true;
                    areaId = 0;
                    if (sale.getArea() != null) {
                        areaId = sale.getArea().getId();
                    }
                    uploadItems = new ArrayList<UploadItem>();
                    for (Image img : sale.getImages()) {
                        UploadItem item = new UploadItem("", new File("/home/webadmin/eez2find.com/gfdeploy/site_war/images/" + img.getImage()));
                        uploadItems.add(item);
                    }
                    saleCategorieId = sale.getSaleCategorie().getId();
                } else {
                    sale = new Sale();
                    sale.setTypeReplyTo("masked email");
                    if (!sessionBean.getAreasCurrentSite().isEmpty()) {
                        if (sessionBean.getEjbSession().getCurrentArea() != null) {
                            areaId = sessionBean.getEjbSession().getCurrentArea().getId();
                        } else {
                            areaId = sessionBean.getEjbSession().getCurrentSite().getAreas().get(1).getId();
                        }
                    }
                    sale.setSaleType("offered");
                    uploadItems = new ArrayList<UploadItem>();
                    try {
                        PostBean postBean = (PostBean) RequestContext.getAttribute("postBean");
                        back = postBean.getBack();
                    } catch (Exception ex) {
                    }
                }
            }
        }
        return sale;
    }

    public void setSale(Sale sale) {
        this.sale = sale;
    }

    public List<Sale> getlistAll() {
        return ejbSaleManager.listAll();
    }

    public String create() {
        ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
        HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();
        HttpSession session = request.getSession();
        if (session.isNew()) {
            try {
                String errorPageURL = externalContext.getRequestContextPath() + "/faces/salePosting/create.jsp";
                externalContext.redirect(errorPageURL);
                FacesMessage msg = new FacesMessage("The session has bean expired");
                msg.setSeverity(FacesMessage.SEVERITY_ERROR);
                FacesContext.getCurrentInstance().addMessage(null, msg);
                return null;
            } catch (IOException ioe) {
                ioe.printStackTrace();
                return null;
            }
        } else {
            try {
                SessionBean sessionBean = (SessionBean) SessionContext.getAttribute("sessionBean");
                if (sessionBean.getEjbSession().getOwner() != null) {
                    sale.setCode((ejbSaleManager.lastCode()) + 1);
                    sale.setType("sale");
                    sale.setUser(sessionBean.getEjbSession().getOwner());
                    sale.setEmail(sessionBean.getEjbSession().getOwner().getEmail());
                    if (sale.getTypeReplyTo().equals("masked email")) {
                        ejbEmail.addAnonymousEmail("sale", sale.getCode(), sale.getEmail());
                    }
                    sale.setPublishDate(new Date(System.currentTimeMillis()));
                    sale.setStatus("active");
                    sale.setCreateDate(new Date(System.currentTimeMillis()));
                    sale.setSite(sessionBean.getEjbSession().getCurrentSite());
                    if (searchMinPrice != null && !searchMinPrice.equals("")) {
                        sale.setPrice(Double.parseDouble(searchMinPrice));
                    } else {
                        sale.setPrice(0.0);
                    }
                    if (areaId != 0) {
                        sale.setArea(ejbAreaManager.find(areaId));
                    }
                    SaleCategorie saleCategorie = ejbSaleCategorieManager.find(saleCategorieId);
                    sale.setSaleCategorie(saleCategorie);
                    sale.setCategorie(saleCategorie.getCategorie());
                    ejbSaleManager.create(sale);
                    if (!uploadItems.isEmpty()) {
                        Sale saleMerge = ejbSaleManager.merge(sale);
                        long code = ejbImageManager.lastCode() + 1;
                        for (UploadItem item : uploadItems) {
                            BufferedImage saleImage = ImageIO.read(item.getFile());
                            int saleImageWidth;
                            int saleImageHeight;
                            if (saleImage.getWidth() >= saleImage.getHeight()) {
                                saleImageWidth = 300;
                                saleImageHeight = saleImage.getHeight() * 300 / saleImage.getWidth();
                            } else {
                                saleImageHeight = 300;
                                saleImageWidth = saleImage.getWidth() * 300 / saleImage.getHeight();
                            }
                            java.awt.Image image = saleImage.getScaledInstance(saleImageWidth, saleImageHeight, java.awt.Image.SCALE_SMOOTH);
                            BufferedImage scaleImage = new BufferedImage(saleImageWidth, saleImageHeight, BufferedImage.TYPE_INT_RGB);
                            Graphics2D g2d = scaleImage.createGraphics();
                            g2d.drawImage(image, 0, 0, null);
                            g2d.dispose();
                            ImageIO.write(scaleImage, "jpg", new File("/home/webadmin/eez2find.com/gfdeploy/site_war/images/image" + code + ".jpg"));
                            Image i = new Image();
                            i.setCode(code);
                            i.setImage("image" + code + ".jpg");
                            i.setSale(saleMerge);
                            ejbImageManager.create(i);
                            sale.getImages().add(i);
                            code++;
                        }
                        sale.setImg(true);
                        ejbSaleManager.update(sale);
                    }
                    FacesMessage msg = new FacesMessage("Your post has been successfully registered.");
                    FacesContext.getCurrentInstance().addMessage(null, msg);
                    FacesMessage msg1 = new FacesMessage("To manage your post,  log into your account.");
                    FacesContext.getCurrentInstance().addMessage(null, msg1);
                    createOk = true;
                    return "success";
                } else {
                    if ((sale.getEmail().length() < 4) || !sale.getEmail().contains("@") || !sale.getEmail().contains(".") || (email1.length() < 4) || !email1.contains("@") || !email1.contains(".") || !sale.getEmail().equals(email1)) {
                        FacesMessage msg = new FacesMessage("The emails address don't equals or invalids");
                        msg.setSeverity(FacesMessage.SEVERITY_ERROR);
                        FacesContext.getCurrentInstance().addMessage(null, msg);
                        return null;
                    }
                    RegisterUser userAccount = ejbUserManager.findUserByEmail(sale.getEmail());
                    if (userAccount != null) {
                        if (userAccount.getStatus().equals("active") || userAccount.getStatus().equals("reactive")) {
                            sale.setUser(userAccount);
                            sale.setCode((ejbSaleManager.lastCode()) + 1);
                            sale.setType("sale");
                            sale.setStatus("pending");
                            sale.setCreateDate(new Date(System.currentTimeMillis()));
                            sale.setSite(sessionBean.getEjbSession().getCurrentSite());
                            if (searchMinPrice != null && !searchMinPrice.equals("")) {
                                sale.setPrice(Double.parseDouble(searchMinPrice));
                            } else {
                                sale.setPrice(0.0);
                            }
                            if (areaId != 0) {
                                sale.setArea(ejbAreaManager.find(areaId));
                            }
                            SaleCategorie saleCategorie = ejbSaleCategorieManager.find(saleCategorieId);
                            sale.setSaleCategorie(saleCategorie);
                            sale.setCategorie(saleCategorie.getCategorie());
                            ejbSaleManager.create(sale);
                            if (!uploadItems.isEmpty()) {
                                Sale saleMerge = ejbSaleManager.merge(sale);
                                long code = ejbImageManager.lastCode() + 1;
                                for (UploadItem item : uploadItems) {
                                    BufferedImage saleImage = ImageIO.read(item.getFile());
                                    int saleImageWidth;
                                    int saleImageHeight;
                                    if (saleImage.getWidth() >= saleImage.getHeight()) {
                                        saleImageWidth = 300;
                                        saleImageHeight = saleImage.getHeight() * 300 / saleImage.getWidth();
                                    } else {
                                        saleImageHeight = 300;
                                        saleImageWidth = saleImage.getWidth() * 300 / saleImage.getHeight();
                                    }
                                    java.awt.Image image = saleImage.getScaledInstance(saleImageWidth, saleImageHeight, java.awt.Image.SCALE_SMOOTH);
                                    BufferedImage scaleImage = new BufferedImage(saleImageWidth, saleImageHeight, BufferedImage.TYPE_INT_RGB);
                                    Graphics2D g2d = scaleImage.createGraphics();
                                    g2d.drawImage(image, 0, 0, null);
                                    g2d.dispose();
                                    ImageIO.write(scaleImage, "jpg", new File("/home/webadmin/eez2find.com/gfdeploy/site_war/images/image" + code + ".jpg"));
                                    Image i = new Image();
                                    i.setCode(code);
                                    i.setImage("image" + code + ".jpg");
                                    i.setSale(saleMerge);
                                    ejbImageManager.create(i);
                                    sale.getImages().add(i);
                                    code++;
                                }
                                sale.setImg(true);
                                ejbSaleManager.update(sale);
                            }
                            FacesMessage msg = new FacesMessage("Your post has been successfully registered.");
                            FacesContext.getCurrentInstance().addMessage(null, msg);
                            FacesMessage msg1 = new FacesMessage("The User Account from this email " + userAccount.getEmail() + " exist.");
                            FacesContext.getCurrentInstance().addMessage(null, msg1);
                            FacesMessage msg2 = new FacesMessage("If you forgot your password or need to reactive your account clik in the link to recovery password.");
                            FacesContext.getCurrentInstance().addMessage(null, msg2);
                            FacesMessage msg3 = new FacesMessage("Please enter in your account and published your posting.");
                            FacesContext.getCurrentInstance().addMessage(null, msg3);
                            linkRPOk = true;
                            createOk = true;
                            return "success";
                        }
                        //userAccount.setDefaultSite(sessionBean.getEjbSession().getCurrentSite());
                        userAccount.setRegisterDate(new Date(System.currentTimeMillis()));
                        Random r = new Random();
                        String token = Long.toString(Math.abs(r.nextLong()), 36);
                        userAccount.setConfirmationCode(token);
                        ejbUserManager.update(userAccount, false);
                        ejbEmail.sendAccountConfirmation(userAccount);
                        sale.setUser(userAccount);
                    } else {
                        RegisterUser registerUser = new RegisterUser();
                        registerUser.setEmail(sale.getEmail());
                        //registerUser.setDefaultSite(sessionBean.getEjbSession().getCurrentSite());
                        registerUser.setNumberOfPostings(50);
                        registerUser.setRegisterDate(new Date(System.currentTimeMillis()));
                        registerUser.setStatus("pending");
                        Random r = new Random();
                        String token = Long.toString(Math.abs(r.nextLong()), 36);
                        registerUser.setConfirmationCode(token);
                        ejbUserManager.create(registerUser);
                        RegisterUser newRegisterUser = ejbUserManager.merge(registerUser);
                        ejbEmail.sendAccountConfirmation(newRegisterUser);
                        sale.setUser(newRegisterUser);
                    }
                    sale.setCode((ejbSaleManager.lastCode()) + 1);
                    sale.setType("sale");
                    sale.setStatus("pending");
                    sale.setCreateDate(new Date(System.currentTimeMillis()));
                    sale.setSite(sessionBean.getEjbSession().getCurrentSite());
                    if (searchMinPrice != null && !searchMinPrice.equals("")) {
                        sale.setPrice(Double.parseDouble(searchMinPrice));
                    } else {
                        sale.setPrice(0.0);
                    }
                    if (areaId != 0) {
                        sale.setArea(ejbAreaManager.find(areaId));
                    }
                    SaleCategorie saleCategorie = ejbSaleCategorieManager.find(saleCategorieId);
                    sale.setSaleCategorie(saleCategorie);
                    sale.setCategorie(saleCategorie.getCategorie());
                    ejbSaleManager.create(sale);
                    if (!uploadItems.isEmpty()) {
                        Sale saleMerge = ejbSaleManager.merge(sale);
                        long code = ejbImageManager.lastCode() + 1;
                        for (UploadItem item : uploadItems) {
                            BufferedImage saleImage = ImageIO.read(item.getFile());
                            int saleImageWidth;
                            int saleImageHeight;
                            if (saleImage.getWidth() >= saleImage.getHeight()) {
                                saleImageWidth = 300;
                                saleImageHeight = saleImage.getHeight() * 300 / saleImage.getWidth();
                            } else {
                                saleImageHeight = 300;
                                saleImageWidth = saleImage.getWidth() * 300 / saleImage.getHeight();
                            }
                            java.awt.Image image = saleImage.getScaledInstance(saleImageWidth, saleImageHeight, java.awt.Image.SCALE_SMOOTH);
                            BufferedImage scaleImage = new BufferedImage(saleImageWidth, saleImageHeight, BufferedImage.TYPE_INT_RGB);
                            Graphics2D g2d = scaleImage.createGraphics();
                            g2d.drawImage(image, 0, 0, null);
                            g2d.dispose();
                            ImageIO.write(scaleImage, "jpg", new File("/home/webadmin/eez2find.com/gfdeploy/site_war/images/image" + code + ".jpg"));
                            Image i = new Image();
                            i.setCode(code);
                            i.setImage("image" + code + ".jpg");
                            i.setSale(saleMerge);
                            ejbImageManager.create(i);
                            sale.getImages().add(i);
                            code++;
                        }
                        sale.setImg(true);
                        ejbSaleManager.update(sale);
                    }
                    FacesMessage msg = new FacesMessage("Your post has been successfully registered.");
                    FacesContext.getCurrentInstance().addMessage(null, msg);
                    FacesMessage msg1 = new FacesMessage("For Administrate your Post eez2find creates an Account for you using the email address " + sale.getEmail() + " to reply this post.");
                    FacesContext.getCurrentInstance().addMessage(null, msg1);
                    FacesMessage msg2 = new FacesMessage("Please active your account from email received and published your posting.");
                    FacesContext.getCurrentInstance().addMessage(null, msg2);
                    createOk = true;
                    return "success";
                }
            } catch (Exception ex) {
                ex.printStackTrace();
                FacesMessage msg = new FacesMessage("Error your Post can't register, maybe the email could not be sent or it doesn't exist");
                msg.setSeverity(FacesMessage.SEVERITY_ERROR);
                FacesContext.getCurrentInstance().addMessage(null, msg);
                return null;
            }
        }
    }

    public String previewCreate() {
        ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
        HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();
        HttpSession session = request.getSession();
        if (session.isNew()) {
            try {
                String errorPageURL = externalContext.getRequestContextPath() + "/faces/salePosting/create.jsp";
                externalContext.redirect(errorPageURL);
                FacesMessage msg = new FacesMessage("The session has bean expired");
                msg.setSeverity(FacesMessage.SEVERITY_ERROR);
                FacesContext.getCurrentInstance().addMessage(null, msg);
                return null;
            } catch (IOException ioe) {
                ioe.printStackTrace();
                return null;
            }
        } else {
            SessionBean sessionBean = (SessionBean) SessionContext.getAttribute("sessionBean");
            if (sessionBean.getEjbSession().getOwner() != null) {
                sale.setEmail(sessionBean.getEjbSession().getOwner().getEmail());
                if (searchMinPrice != null && !searchMinPrice.equals("")) {
                    sale.setPrice(Double.parseDouble(searchMinPrice));
                } else {
                    sale.setPrice(0.0);
                }
                return "success";
            } else {
                if ((sale.getEmail().length() < 4) || !sale.getEmail().contains("@") || !sale.getEmail().contains(".") || (email1.length() < 4) || !email1.contains("@") || !email1.contains(".") || !sale.getEmail().equals(email1)) {
                    FacesMessage msg = new FacesMessage("The emails address don't equals or invalids");
                    msg.setSeverity(FacesMessage.SEVERITY_ERROR);
                    FacesContext.getCurrentInstance().addMessage(null, msg);
                    return null;
                }
                if (searchMinPrice != null && !searchMinPrice.equals("")) {
                    sale.setPrice(Double.parseDouble(searchMinPrice));
                } else {
                    sale.setPrice(0.0);
                }
                return "success";
            }
        }
    }

    public String update() {
        ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
        HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();
        HttpSession session = request.getSession();
        if (session.isNew()) {
            try {
                String errorPageURL = externalContext.getRequestContextPath() + "/faces/welcome.jsp";
                externalContext.redirect(errorPageURL);
                FacesMessage msg = new FacesMessage("The session has bean expired");
                msg.setSeverity(FacesMessage.SEVERITY_ERROR);
                FacesContext.getCurrentInstance().addMessage(null, msg);
                return null;
            } catch (IOException ioe) {
                ioe.printStackTrace();
                return null;
            }
        } else {
            try {
                SessionBean sessionBean = (SessionBean) SessionContext.getAttribute("sessionBean");
                if (sale.getTypeReplyTo().equals("masked email") && !maskedEmail) {
                    ejbEmail.addAnonymousEmail("sale", sale.getCode(), sale.getEmail());
                }
                if (!sale.getTypeReplyTo().equals("masked email") && maskedEmail) {
                    ejbEmail.deleteAnonymousEmail("sale", sale.getCode(), sale.getEmail());
                }
                if (searchMinPrice != null && !searchMinPrice.equals("")) {
                    sale.setPrice(Double.parseDouble(searchMinPrice));
                } else {
                    sale.setPrice(0.0);
                }
                if (areaId != 0) {
                    sale.setArea(ejbAreaManager.find(areaId));
                } else {
                    sale.setArea(null);
                }
                SaleCategorie saleCategorie = ejbSaleCategorieManager.find(saleCategorieId);
                sale.setSaleCategorie(saleCategorie);
                sale.setCategorie(saleCategorie.getCategorie());
                if (sale.getImages().isEmpty()) {
                    if (!uploadItems.isEmpty()) {
                        long code = ejbImageManager.lastCode() + 1;
                        for (UploadItem item : uploadItems) {
                            BufferedImage saleImage = ImageIO.read(item.getFile());
                            int saleImageWidth;
                            int saleImageHeight;
                            if (saleImage.getWidth() >= saleImage.getHeight()) {
                                saleImageWidth = 300;
                                saleImageHeight = saleImage.getHeight() * 300 / saleImage.getWidth();
                            } else {
                                saleImageHeight = 300;
                                saleImageWidth = saleImage.getWidth() * 300 / saleImage.getHeight();
                            }
                            java.awt.Image image = saleImage.getScaledInstance(saleImageWidth, saleImageHeight, java.awt.Image.SCALE_SMOOTH);
                            BufferedImage scaleImage = new BufferedImage(saleImageWidth, saleImageHeight, BufferedImage.TYPE_INT_RGB);
                            Graphics2D g2d = scaleImage.createGraphics();
                            g2d.drawImage(image, 0, 0, null);
                            g2d.dispose();
                            ImageIO.write(scaleImage, "jpg", new File("/home/webadmin/eez2find.com/gfdeploy/site_war/images/image" + code + ".jpg"));
                            Image i = new Image();
                            i.setCode(code);
                            i.setImage("image" + code + ".jpg");
                            i.setSale(sale);
                            ejbImageManager.create(i);
                            sale.getImages().add(i);
                            code++;
                        }
                        sale.setImg(true);
                    }
                } else {
                    if (!uploadItems.isEmpty()) {
                        long code = ejbImageManager.lastCode() + 1;
                        int index = 0;
                        for (UploadItem item : uploadItems) {
                            if (!item.getFileName().equals("")) {
                                BufferedImage saleImage = ImageIO.read(item.getFile());
                                int saleImageWidth;
                                int saleImageHeight;
                                if (saleImage.getWidth() >= saleImage.getHeight()) {
                                    saleImageWidth = 300;
                                    saleImageHeight = saleImage.getHeight() * 300 / saleImage.getWidth();
                                } else {
                                    saleImageHeight = 300;
                                    saleImageWidth = saleImage.getWidth() * 300 / saleImage.getHeight();
                                }
                                java.awt.Image image = saleImage.getScaledInstance(saleImageWidth, saleImageHeight, java.awt.Image.SCALE_SMOOTH);
                                BufferedImage scaleImage = new BufferedImage(saleImageWidth, saleImageHeight, BufferedImage.TYPE_INT_RGB);
                                Graphics2D g2d = scaleImage.createGraphics();
                                g2d.drawImage(image, 0, 0, null);
                                g2d.dispose();
                                if (index < sale.getImages().size()) {
                                    ImageIO.write(scaleImage, "jpg", new File("/home/webadmin/eez2find.com/gfdeploy/site_war/images/image" + sale.getImages().get(index).getCode() + ".jpg"));
                                } else {
                                    ImageIO.write(scaleImage, "jpg", new File("/home/webadmin/eez2find.com/gfdeploy/site_war/images/image" + code + ".jpg"));
                                    Image i = new Image();
                                    i.setCode(code);
                                    i.setImage("image" + code + ".jpg");
                                    i.setSale(sale);
                                    ejbImageManager.create(i);
                                    sale.getImages().add(i);
                                    code++;
                                }
                            }
                            index++;
                        }
                        for (int i = index; i < sale.getImages().size(); i++) {
                            File f = new File("/home/webadmin/eez2find.com/gfdeploy/site_war/images/" + sale.getImages().get(i).getImage());
                            f.delete();
                            ejbImageManager.delete(sale.getImages().get(i));
                            sale.getImages().remove(i);
                        }
                    } else {
                        for (Image img : sale.getImages()) {
                            File f = new File("/home/webadmin/eez2find.com/gfdeploy/site_war/images/" + img.getImage());
                            f.delete();
                            ejbImageManager.delete(img);
                        }
                        sale.getImages().clear();
                        sale.setImg(false);
                    }
                }
                ejbSaleManager.update(sale);
                FacesMessage msg = new FacesMessage("Successful edit your Post");
                FacesContext.getCurrentInstance().addMessage(null, msg);
                sessionBean.getEjbSession().setSale(null);
                SessionContext.removeAttribute("saleBean");
                return "success";
            } catch (Exception ex) {
                ex.printStackTrace();
                FacesMessage msg = new FacesMessage("Error your Post can't edit");
                msg.setSeverity(FacesMessage.SEVERITY_ERROR);
                FacesContext.getCurrentInstance().addMessage(null, msg);
                return null;
            }
        }
    }

    public String previewUpdate() {
        if (searchMinPrice != null && !searchMinPrice.equals("")) {
                    sale.setPrice(Double.parseDouble(searchMinPrice));
                } else {
                    sale.setPrice(0.0);
                }
                return "previewUpdate";
    }
    
    public long getAreaId() {
        return areaId;
    }

    public void setAreaId(long areaId) {
        this.areaId = areaId;
    }

    public Area getArea() {
        return ejbAreaManager.find(areaId);
    }

    public List<Location> getLocationsSaleArea() {
        try {
            return ejbLocationManager.locationsArea(ejbAreaManager.find(areaId));
        } catch (Exception ex) {
            return new ArrayList<Location>();
        }
    }

    public boolean isCreateOk() {
        return createOk;
    }

    public void setCreateOk(boolean createOk) {
        this.createOk = createOk;
    }

    public boolean isLinkRPOk() {
        return linkRPOk;
    }

    public void setLinkRPOk(boolean linkRPOk) {
        this.linkRPOk = linkRPOk;
    }

    public String homeUser() {
        SessionContext.removeAttribute("saleBean");
        return "homeUser";
    }

    public int getBack() {
        return back;
    }

    public void setBack(int back) {
        this.back = back;
    }

    public long getSaleCategorieId() {
        if (saleCategorieId == 0) {
            try {
                PostBean postBean = (PostBean) RequestContext.getAttribute("postBean");
                saleCategorieId = postBean.getCategorieId();
            } catch (Exception ex) {
            }
        }
        return saleCategorieId;
    }

    public void setSaleCategorieId(long saleCategorieId) {
        this.saleCategorieId = saleCategorieId;
    }

    public List<Sale> getListSales() {
        ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
        HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();
        HttpSession session = request.getSession();
        if (session.isNew()) {
            try {
                String errorPageURL = externalContext.getRequestContextPath() + "/faces/salePosting/list.jsp";
                externalContext.redirect(errorPageURL);
                FacesMessage msg = new FacesMessage("The session has bean expired");
                msg.setSeverity(FacesMessage.SEVERITY_ERROR);
                FacesContext.getCurrentInstance().addMessage(null, msg);
                return null;
            } catch (IOException ioe) {
                ioe.printStackTrace();
                return null;
            }
        } else {
            String consult = "";
            boolean saleC = false;
            if (saleCategorieId > 0) {
                consult = consult + " AND s.saleCategorie=:saleCategorie";
                saleC = true;
            }
            if (searchType != null && searchType.equals("offered")) {
                consult = consult + " AND s.saleType='offered'";
            }
            if (searchType != null && searchType.equals("wanted")) {
                consult = consult + " AND s.saleType='wanted'";
            }
            if (searchMinPrice != null && !searchMinPrice.equals("") && searchMaxPrice != null && !searchMaxPrice.equals("") && Double.parseDouble(searchMinPrice) > Double.parseDouble(searchMaxPrice)) {
                FacesMessage msg = new FacesMessage("The min price should be smaller than max price");
                msg.setSeverity(FacesMessage.SEVERITY_ERROR);
                FacesContext.getCurrentInstance().addMessage(null, msg);
            } else if ((searchMinPrice != null && !searchMinPrice.equals("")) || (searchMaxPrice != null && !searchMaxPrice.equals(""))) {
                if (searchMinPrice != null && !searchMinPrice.equals("")) {
                    consult = consult + " AND s.price>=" + searchMinPrice;
                } else {
                    consult = consult + " AND s.price>0";
                }
                if (searchMaxPrice != null && !searchMaxPrice.equals("")) {
                    consult = consult + " AND s.price<=" + searchMaxPrice;
                }
            }
            if (hasImage) {
                consult = consult + " AND (s.description like '%<img src=%' OR s.img=1)";
            }
            if (searchValue != null && !searchValue.equals("")) {
                if (onlySearchTitles) {
                    consult = consult + " AND s.title like '%" + searchValue + "%'";
                } else {
                    consult = consult + " AND (s.title like '%" + searchValue + "%' OR s.description like '%" + searchValue + "%')";
                }
            }
            SessionBean sessionBean = (SessionBean) SessionContext.getAttribute("sessionBean");
            if (sessionBean.getEjbSession().getCurrentArea() == null) {
                return ejbSaleManager.listSalesSite(sessionBean.getEjbSession().getCurrentSite(), saleC, ejbSaleCategorieManager.find(saleCategorieId), consult);
            } else {
                return ejbSaleManager.listSalesArea(sessionBean.getEjbSession().getCurrentArea(), saleC, ejbSaleCategorieManager.find(saleCategorieId), consult);
            }
        }
    }

    public String backView() {
        sale = null;
        return "backSale" + back;
    }

    public String backCreate() {
        SessionContext.removeAttribute("saleBean");
        return "back" + back;
    }

    public String backEdit() {
        SessionContext.removeAttribute("saleBean");
        return "back";
    }

    public String getEmail1() {
        return email1;
    }

    public void setEmail1(String email1) {
        this.email1 = email1;
    }

    public Date getToDay() {
        return new Date(System.currentTimeMillis());
    }

    public String getDescription() {
        try {
            if (sale.getDescription().contains("\n")) {
                return sale.getDescription().replaceAll("\n", "<br/>");
            } else {
                return sale.getDescription().replaceAll("\r", "<br/>");
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            return "Do not Message";
        }
    }

    public String getSearchValue() {
        if(searchValue==null){
            try {
                PostBean postBean = (PostBean) RequestContext.getAttribute("postBean");
                searchValue = postBean.getSearchValue();
            } catch (Exception ex) {
            }
        }
        return searchValue;
    }

    public void setSearchValue(String searchValue) {
        this.searchValue = searchValue;
    }

    public boolean isOnlySearchTitles() {
        return onlySearchTitles;
    }

    public void setOnlySearchTitles(boolean onlySearchTitles) {
        this.onlySearchTitles = onlySearchTitles;
    }

    public boolean isHasImage() {
        return hasImage;
    }

    public void setHasImage(boolean hasImage) {
        this.hasImage = hasImage;
    }

    public String getSearchType() {
        return searchType;
    }

    public void setSearchType(String searchType) {
        this.searchType = searchType;
    }

    public String getSearchMinPrice() {
        return searchMinPrice;
    }

    public void setSearchMinPrice(String searchMinPrice) {
        this.searchMinPrice = searchMinPrice;
    }

    public String getSearchMaxPrice() {
        return searchMaxPrice;
    }

    public void setSearchMaxPrice(String searchMaxPrice) {
        this.searchMaxPrice = searchMaxPrice;
    }

    public void paint(OutputStream out, Object data) throws IOException {
        UploadItem item = uploadItems.get((Integer) data);
        BufferedImage img = ImageIO.read(item.getFile());
        int imgWidth;
        int imgHeight;
        if (img.getWidth() >= img.getHeight()) {
            imgWidth = 100;
            imgHeight = img.getHeight() * 100 / img.getWidth();
        } else {
            imgHeight = 100;
            imgWidth = img.getWidth() * 100 / img.getHeight();
        }
        java.awt.Image image = img.getScaledInstance(imgWidth, imgHeight, java.awt.Image.SCALE_SMOOTH);
        BufferedImage scaleImg = new BufferedImage(imgWidth, imgHeight, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = scaleImg.createGraphics();
        g2d.drawImage(image, 0, 0, null);
        g2d.dispose();

        ImageIO.write(scaleImg, "jpg", out);
    }

    public void paintPreview(OutputStream out, Object data) throws IOException {
        UploadItem item = uploadItems.get((Integer) data);
        BufferedImage img = ImageIO.read(item.getFile());
        int imgWidth;
        int imgHeight;
        if (img.getWidth() >= img.getHeight()) {
            imgWidth = 300;
            imgHeight = img.getHeight() * 300 / img.getWidth();
        } else {
            imgHeight = 300;
            imgWidth = img.getWidth() * 300 / img.getHeight();
        }
        java.awt.Image image = img.getScaledInstance(imgWidth, imgHeight, java.awt.Image.SCALE_SMOOTH);
        BufferedImage scaleImg = new BufferedImage(imgWidth, imgHeight, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = scaleImg.createGraphics();
        g2d.drawImage(image, 0, 0, null);
        g2d.dispose();

        ImageIO.write(scaleImg, "jpg", out);
    }

    public void deleteItem() {
        uploadItems.remove(row);
    }

    public void deleteItems() {
        uploadItems.clear();
    }

    public int getItemsSize() {
        return uploadItems.size();
    }

    public List<UploadItem> getUploadItems() {
        return uploadItems;
    }

    public void setUploadItems(List<UploadItem> uploadItems) {
        this.uploadItems = uploadItems;
    }

    public int getRow() {
        return row;
    }

    public void setRow(int row) {
        this.row = row;
    }

    public int getPage() {
        if (page == 0) {
            page = 1;
        }
        return page;
    }

    public void setPage(int page) {
        this.page = page;
    }

    public int getContador() {
        try {
            return 20000 - sale.getDescription().length();
        } catch (Exception ex) {
            return 20000;
        }
    }

    public void setContador(int contador) {}
    

    public void flaggingMiscategorized(){
        try {
            sale.setMiscategorized(ejbSaleManager.merge(sale).getMiscategorized()+1);
            ejbSaleManager.update(sale);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    
    public void flaggingProhibited(){
        try {
            sale.setProhibited(ejbSaleManager.merge(sale).getProhibited()+1);
            ejbSaleManager.update(sale);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    
    public void flaggingSpam(){
        try {
            sale.setSpam(ejbSaleManager.merge(sale).getSpam()+1);
            ejbSaleManager.update(sale);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    
    public void flaggingBest(){
        try {
            sale.setBest(ejbSaleManager.merge(sale).getBest()+1);
            ejbSaleManager.update(sale);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
